package com.wwj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wwj.reggie.common.R;
import com.wwj.reggie.dto.DishDto;
import com.wwj.reggie.entity.Category;
import com.wwj.reggie.entity.Dish;
import com.wwj.reggie.entity.DishFlavor;
import com.wwj.reggie.service.CategoryService;
import com.wwj.reggie.service.DishFlavorService;
import com.wwj.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清理对应分类的缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return  R.success("");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){

        //构造分页构造器
        Page<Dish> pageInfo = new Page(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null, Dish::getName, name).eq(Dish::getIsDeleted, 0);
        //添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);

        //执行查询
        dishService.page(pageInfo, lqw);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        //将pageInfo中的records取出
        List<Dish> records = pageInfo.getRecords();


        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();  //遍历取出records中的分类Id
            Category category = categoryService.getById(categoryId);  //通过Id查询分类对象
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);  //取出分类对象中封装的分类名称，并赋给dishDto

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品及其口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> dishUpdate(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清理对应分类的缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        return  R.success("");
    }

    /**
     * 菜品状态：修改————批量修改
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> statusUpdate(@PathVariable int status , String[] ids){

        List<Dish> dishes = new ArrayList<>();

        for (String id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishes.add(dish);
        }

        dishService.updateBatchById(dishes);

        return R.success("");
    }

    /**
     * 删除————批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> dishDelete(@RequestParam List<Long> ids){
        log.info(ids.toString());
        dishService.deleteDish(ids);
        return R.success("");
    }

    /**
     * 套餐添加中根据菜品分类查询菜品数据
     * @param dish
     * @return
     */
   /*
    @GetMapping("/list")
    public R<List<Dish>> dishList(Dish dish){
        //构造条件对象
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getIsDeleted, 0)
                .eq(Dish::getStatus, 1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lqw);

        return R.success(list);
    }
    */

    @GetMapping("/list")
    public R<List<DishDto>> dishList(Dish dish){

        List<DishDto> dishDtoList =null;

        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        // 从Redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        //构造条件对象
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getIsDeleted, 0)
                .eq(Dish::getStatus, 1);
        //添加排序条件
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lqw);


        dishDtoList = list.stream().map((item) -> {

            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            LambdaQueryWrapper<DishFlavor> flavorLQW = new LambdaQueryWrapper<>();
            flavorLQW.eq(DishFlavor::getDishId, item.getId());

            List<DishFlavor> dishFlavors = dishFlavorService.list(flavorLQW);

            dishDto.setFlavors(dishFlavors);

            return  dishDto;
        }).collect(Collectors.toList());

        //将从数据库中查询到的数据缓存到redis中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
